package com.zahb.qadx.ui.activity.videopage;


import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;

import com.bokecc.sdk.mobile.drm.DRMServer;
import com.bokecc.sdk.mobile.exception.HuodeException;
import com.bokecc.sdk.mobile.play.DWMediaPlayer;
import com.bokecc.sdk.mobile.play.MediaMode;
import com.bokecc.sdk.mobile.play.OnDreamWinErrorListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.util.ClickCheck;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;

import java.io.IOException;
import java.util.Map;

/**
 * LEB .2021.3.12
 * 微视频播放器
 */
public class MicroVideoPlayerFragment extends Fragment implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, TextureView.SurfaceTextureListener,
        DWMediaPlayer.OnPreparedListener, DWMediaPlayer.OnInfoListener, DWMediaPlayer.OnBufferingUpdateListener,
        DWMediaPlayer.OnCompletionListener, OnDreamWinErrorListener, DWMediaPlayer.OnErrorListener {

    private TextureView mTvVideo;
    private Surface mSurface;
    private DWMediaPlayer mDWMediaPlayer;
    // USER_ID
    private static final String USER_ID = "055AE5CC4411D5CB";
    // API_KEY
    private static final String API_KEY = "BnPoazIUwhRa1Sk5AVBP7hk8dDk7a3Aw";
    // 视频ID
    private String videoId;
    //第几页
    private int playvalue;
    // 开通授权验证播放功能的需要配置授权验证码，
    // 没有开通授权验证播放功能的，verificationCode填null
    private String verificationCode = null;

    // 当前清晰度
    private int mCurrentDefinition;
    // 切换清晰度时播放进度
    private int mSwitchDefPos;
    // 最大可拖动播放时间
    private int mMaxSeekTime;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private static final long BOTTOM_LAYOUT_SHOW_TIME = 5000L;
    private boolean mIsViewDestroyed;
    private boolean mIsPrepared;
    private boolean mIsAudio;
    private boolean mIsAutoPaused;
    private boolean mIsSeeking;// 正在拖动进度

    private ConstraintLayout mContainerLayout;
    private ImageView mIvAudioGif;
    private View mBottomLayout;
    private ImageView mIvPlayPause;
    private SeekBar mSeekBar;
    private TextView mTvTimeInfo;
    private TextView mTvDefinition;
    private LinearLayoutCompat mListDefinitions;
    private ImageView mIvFullHalf;
    private TextView mTvTitleBack;
    private LinearLayoutCompat mLayoutPlayedTime;
    private TextView mTvPlayedTime;

    private onFullHalfViewClickListener mOnFullHalfViewClickListener;

    private boolean currentPage=false;

    private RelativeLayout video_switch;
    private ImageView mSwitch_figure;
    private String title;
    private TextView title_name;
    private  boolean doubleswitch=true;
    private AVLoadingIndicatorView load_the_film;
    private ImageView mFull_screen;//全屏
    private   DRMServer drmServer=new DRMServer();
    public void setOnFullHalfViewClickListener(onFullHalfViewClickListener listener) {
        mOnFullHalfViewClickListener = listener;
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    public interface onFullHalfViewClickListener {
        void onRequestFull(ImageView view);

        void onRequestHalf(ImageView view);
    }

    private onStateChangedListener mOnStateChangedListener;

    public void setOnStateChangedListener(onStateChangedListener onStateChangedListener) {
        mOnStateChangedListener = onStateChangedListener;
    }

    public interface onStateChangedListener {
        void onPause(int playedTime, int totalTime);

        void onChangeMedia(int playedTime, int totalTime);

        void onCompletion(int playedTime, int totalTime);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mIsSeeking = true;
        mHandler.removeCallbacks(mHideRunnable);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mIsSeeking = false;
        mHandler.postDelayed(mHideRunnable, BOTTOM_LAYOUT_SHOW_TIME);
        if (mIsPrepared) {
            int max = seekBar.getMax();
            int progress = seekBar.getProgress();
            int duration = mDWMediaPlayer.getDuration();
            int seekPosition = duration * progress / max;
            if (mMaxSeekTime < 0) {// 不限制拖动进度
                mDWMediaPlayer.seekTo(seekPosition);
            } else {// 限制拖动进度
                if (seekPosition < mMaxSeekTime) {
                    mDWMediaPlayer.seekTo(seekPosition);
                } else {
                    mDWMediaPlayer.seekTo(mMaxSeekTime);
                }
            }
        }
    }

    public static MicroVideoPlayerFragment newInstance(String videoId, boolean isAudio) {
        return newInstance(videoId, isAudio, -1);
    }
    public static MicroVideoPlayerFragment newInstancess(String videoId, boolean isAudio,int type,String title) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        args.putString("videoId", videoId);
        args.putBoolean("isAudio", isAudio);
        args.putInt("maxTime", -1);
        args.putString("title", title);
        MicroVideoPlayerFragment fragment = new MicroVideoPlayerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static MicroVideoPlayerFragment newInstance(String videoId, boolean isAudio, int maxTime) {
        Bundle args = new Bundle();
        args.putString("videoId", videoId);
        args.putBoolean("isAudio", isAudio);
        args.putInt("maxTime", maxTime);
//        args.putInt("playvalue", playvalue);
        MicroVideoPlayerFragment fragment = new MicroVideoPlayerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        Bundle args = getArguments();
        if (args != null) {
            playvalue = args.getInt("type");
            title=args.getString("title");
            videoId = args.getString("videoId");
            mIsAudio = args.getBoolean("isAudio", false);
            int maxTime = args.getInt("maxTime", -1);
            if (maxTime < 0) {
                mMaxSeekTime = -1;
            } else {
                mMaxSeekTime = maxTime * 1000;
            }
        }
        Log.e("走了","onCreate"+playvalue);

    }


    @Override
    public void onResume() {
        super.onResume();
        if (mDWMediaPlayer != null && !mDWMediaPlayer.isPlaying() && mIsPrepared ) {
            start();
            mIsAutoPaused = false;
        }else {
            currentPage=true;
        }
        title_name.setText(title);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mDWMediaPlayer != null && mDWMediaPlayer.isPlaying()) {
            pause();
            mIsAutoPaused = true;
            Log.e("走了ss","onPause"+playvalue);
        }
        currentPage=false;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_micro_video_player, container, false);
        title_name=rootView.findViewById(R.id.title_name);
        mFull_screen=rootView.findViewById(R.id.full_screen);
        mFull_screen.setOnClickListener(this);
        load_the_film=rootView.findViewById(R.id.load_the_film);
        mContainerLayout = rootView.findViewById(R.id.container_layout);
        mTvVideo = rootView.findViewById(R.id.tv_video);
        mSwitch_figure=rootView.findViewById(R.id.mSwitch_figure);
        video_switch=rootView.findViewById(R.id.video_switch);
        mTvVideo.setSurfaceTextureListener(this);
        mTvVideo.setOnClickListener(this);
        mIvAudioGif = rootView.findViewById(R.id.iv_audio_gif);
        mBottomLayout = rootView.findViewById(R.id.bottom_layout);
        mIvPlayPause = rootView.findViewById(R.id.iv_play_pause);
        mIvPlayPause.setOnClickListener(this);
        mSeekBar = rootView.findViewById(R.id.seek_bar);
        mSeekBar.setOnSeekBarChangeListener(this);
        //mSeekBar.setOnTouchListener((v, event) -> true);// 禁止拖动
        mTvTimeInfo = rootView.findViewById(R.id.tv_time_info);
        mTvDefinition = rootView.findViewById(R.id.tv_definition);
        mTvDefinition.setOnClickListener(this);
        mListDefinitions = rootView.findViewById(R.id.list_definition);
        mIvFullHalf = rootView.findViewById(R.id.iv_full_half);
        mIvFullHalf.setOnClickListener(this);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//            mIvFullHalf.setImageResource(R.drawable.ic_video_play_full);

        } else {
//            mIvFullHalf.setImageResource(R.drawable.ic_video_play_half);

        }

        mTvTitleBack = rootView.findViewById(R.id.tv_title_back);
        mTvTitleBack.setVisibility(View.GONE);
        mTvTitleBack.setOnClickListener(this);
        mLayoutPlayedTime = rootView.findViewById(R.id.layout_played_time);
        mTvPlayedTime = rootView.findViewById(R.id.tv_played_time);
        load_the_film.show();
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIsViewDestroyed = false;
        initDWMediaPlayer();
    }

    @Override
    public void onDestroyView() {
        Log.e("走了sss","111onDestroyView"+playvalue);
        mIsViewDestroyed = true;
        drmServer.disconnectCurrentStream();
        if (mDWMediaPlayer != null) {
            pause();
            mDWMediaPlayer.stop();
            mDWMediaPlayer.release();
        }
        mIsPrepared = false;
        super.onDestroyView();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_video:
                if (mIsPrepared) {
                    mBottomLayout.setVisibility(View.VISIBLE);
                    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                        mTvTitleBack.setVisibility(View.GONE);
                    } else {
                        mTvTitleBack.setVisibility(View.VISIBLE);
                    }

                    mHandler.removeCallbacks(mHideRunnable);
                    mHandler.postDelayed(mHideRunnable, BOTTOM_LAYOUT_SHOW_TIME);
                    //双击开关
                    if (doubleswitch){
                        if (ClickCheck.isFastClick()){
                            pause();
                            mSwitch_figure.setVisibility(View.VISIBLE);
                            doubleswitch=false;
                            return;
                        }
                    }else {
                        mSwitch_figure.setVisibility(View.GONE);
                        start();
                        doubleswitch=true;
                    }

                }
                break;
            case R.id.iv_play_pause:
                if (mDWMediaPlayer.isPlaying()) {
                    pause();
                    mIsAutoPaused = false;
                    doubleswitch=false;
                    mSwitch_figure.setVisibility(View.VISIBLE);
                } else {
                    doubleswitch=true;
                    start();
                    mSwitch_figure.setVisibility(View.GONE);
                }

                break;

            case R.id.tv_definition:
                currentPage=true;
                if (mListDefinitions.getVisibility() == View.GONE) {
                    mListDefinitions.setVisibility(View.VISIBLE);
                    mHandler.removeCallbacks(mHideRunnable);
                } else {
                    mListDefinitions.setVisibility(View.GONE);
                }
                break;

            case  R.id.iv_full_half:
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    // 设为水平播放
                    if (mOnFullHalfViewClickListener != null){
                        mOnFullHalfViewClickListener.onRequestFull(mIvFullHalf);
                        mFull_screen.setVisibility(View.GONE);
                    }

                } else {
                    // 设为垂直播放
                    if (mOnFullHalfViewClickListener != null){
                        mOnFullHalfViewClickListener.onRequestHalf(mIvFullHalf);
                        mFull_screen.setVisibility(View.VISIBLE);

                    }

                }

                break;
            case  R.id.full_screen:
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    // 设为水平播放
                    if (mOnFullHalfViewClickListener != null){
                        mOnFullHalfViewClickListener.onRequestFull(mIvFullHalf);
                    }

                } else {
                    // 设为垂直播放
                    if (mOnFullHalfViewClickListener != null){
                        mOnFullHalfViewClickListener.onRequestHalf(mIvFullHalf);

                    }

                }

                break;


            case   R.id.tv_title_back:
                if (getActivity() != null)
                    getActivity().onBackPressed();
                break;


        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mIvFullHalf.setImageResource(R.drawable.ic_video_play_full);
            mTvTitleBack.setVisibility(View.GONE);
            mFull_screen.setVisibility(View.VISIBLE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mIvFullHalf.setImageResource(R.drawable.ic_video_play_half);
            mTvTitleBack.setVisibility(View.VISIBLE);
            mFull_screen.setVisibility(View.GONE);

        }
        mHandler.postDelayed(this::updateVideoViewSize, 200);
    }

    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        mSurface = new Surface(surface);
        mDWMediaPlayer.setSurface(mSurface);
    }

    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.e("走了ss","onPrepared"+playvalue);
        mIsPrepared = true;
        updateVideoViewSize();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mFull_screen.setVisibility(View.GONE);
        }else {
            if (mDWMediaPlayer.getVideoWidth()>mDWMediaPlayer.getVideoHeight()){
                mFull_screen.setVisibility(View.VISIBLE);
            }else {
                mFull_screen.setVisibility(View.GONE);
            }
        }

        Log.e("宽高",mDWMediaPlayer.getVideoWidth()+"高"+mDWMediaPlayer.getVideoHeight());
        updateDefinitionView();
        mTvTitleBack.setText(mDWMediaPlayer.getVideoTitle());
        if (mSwitchDefPos > 0)
            mDWMediaPlayer.seekTo(mSwitchDefPos);
        if (mMaxSeekTime > 0) {
            mLayoutPlayedTime.setVisibility(View.VISIBLE);
            mTvPlayedTime.setText(millisecondsToMinuteSecondStr(mMaxSeekTime));
            mLayoutPlayedTime.postDelayed(() -> mLayoutPlayedTime.setVisibility(View.GONE), 1000);
        }
            if (currentPage){
                currentPage=false;
                start();
            }
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        mSeekBar.setSecondaryProgress(percent);

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mIvPlayPause.setImageResource(R.drawable.ic_video_play_small);
        if (mOnStateChangedListener != null)
            mOnStateChangedListener.onCompletion(mDWMediaPlayer.getDuration() / 1000, mDWMediaPlayer.getDuration() / 1000);
    }

    @Override
    public void onPlayError(HuodeException e) {
        e.printStackTrace();
        Log.e("onPlayError",e.getErrorCode()+"");
        if (mDWMediaPlayer != null) {
//            pause();
//            mDWMediaPlayer.stop();
            mDWMediaPlayer.release();
            Log.e("onPlayError",e.getErrorCode()+"1212");
        }
        initDWMediaPlayer();

    }

    // 初始化播放器
    private void initDWMediaPlayer() {

        mDWMediaPlayer = new DWMediaPlayer();
        mDWMediaPlayer.setOnPreparedListener(this);
        mDWMediaPlayer.setOnInfoListener(this);
        mDWMediaPlayer.setOnBufferingUpdateListener(this);
        mDWMediaPlayer.setOnCompletionListener(this);
        mDWMediaPlayer.setOnDreamWinErrorListener(this);
        // 播放DRM加密视频需要这行代码，播放非加密视频不需要
        try {
            drmServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mDWMediaPlayer.setDRMServerPort(drmServer.getPort());
        // 设置视频播放信息
        mDWMediaPlayer.setVideoPlayInfo(videoId, USER_ID, API_KEY, verificationCode, getContext());
//        if (mSurface != null)
//            mDWMediaPlayer.setSurface(mSurface);
        // 重置DRMServer，播放非加密视频不需要
//        BaseApplication.getContext().getDrmServer().reset();
        drmServer.reset();
        if (mIsAudio) {
            mDWMediaPlayer.setDefaultPlayMode(MediaMode.AUDIO, null);
        } else {
            mDWMediaPlayer.setDefaultPlayMode(MediaMode.VIDEO, null);
        }
        mDWMediaPlayer.setAudioPlay(mIsAudio);
        mCurrentDefinition = DWMediaPlayer.NORMAL_DEFINITION;
        mDWMediaPlayer.setDefaultDefinition(mCurrentDefinition);
        mSwitchDefPos = 0;
        mDWMediaPlayer.prepareAsync();
    }

    // 更新视频播放控件的尺寸
    private void updateVideoViewSize() {

        if (!mIsPrepared) return;
        if (mIsAudio) return;
        int videoWidth = mDWMediaPlayer.getVideoWidth();
        int videoHeight = mDWMediaPlayer.getVideoHeight();
        double videoRatio = 1.0d * videoWidth / videoHeight;
        Log.i("size", "videoWidth=" + videoWidth + ", videoHeight=" + videoHeight + ", videoRatio=" + videoRatio);
        if (videoWidth>videoHeight){
            mIvFullHalf.setVisibility(View.VISIBLE);
        }else {
            mIvFullHalf.setVisibility(View.INVISIBLE);
        }

        mContainerLayout.post(() -> {
            int viewWidth = mContainerLayout.getWidth();
            int viewHeight = mContainerLayout.getHeight();
            double viewRatio = 1.0d * viewWidth / viewHeight;
            Log.i("size", "viewWidth=" + viewWidth + ", viewHeight=" + viewHeight + ", viewRatio=" + viewRatio);
            if (viewRatio > videoRatio) {
                viewWidth = (int) (viewHeight * videoRatio);
            } else if (viewRatio < videoRatio) {
                viewHeight = (int) (viewWidth / videoRatio);
            }
            ConstraintSet set = new ConstraintSet();
            set.clone(mContainerLayout);
            set.constrainWidth(mTvVideo.getId(), viewWidth);
            set.constrainHeight(mTvVideo.getId(), viewHeight);
            set.applyTo(mContainerLayout);


        });
    }

    // 设置当前清晰度，切换清晰度
    private void updateDefinitionView() {
        if (mIsAudio) {
            mTvDefinition.setVisibility(View.GONE);
        } else {
            mCurrentDefinition = mDWMediaPlayer.getDefinitionCode();
            Map<String, Integer> definitions = mDWMediaPlayer.getDefinitions();
            mListDefinitions.removeAllViews();
            int padding = DisplayUtil.dip2px2(5f);
            if (definitions != null) {
                for (String key : definitions.keySet()) {
                    Integer definition = definitions.get(key);
                    if (definition != null) {
                        TextView textView = new TextView(getContext());
                        ViewCompat.setPaddingRelative(textView, padding, padding, padding, padding);
                        textView.setText(key);
                        textView.setTextSize(16f);
                        textView.setTextColor(Color.WHITE);
                        textView.setOnClickListener(v -> {
                            mListDefinitions.setVisibility(View.GONE);
                            if (mCurrentDefinition == definition) return;
                            mSwitchDefPos = mDWMediaPlayer.getCurrentPosition();
                            mDWMediaPlayer.reset();
                            mDWMediaPlayer.setSurface(mSurface);
                            drmServer.reset();
                            mIsPrepared = false;
                            mDWMediaPlayer.setDefaultDefinition(definition);
                            try {
                                mDWMediaPlayer.setDefinition(getContext(), definition);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
                        mListDefinitions.addView(textView, 0);
                        if (definition == mCurrentDefinition) {
                            ViewCompat.setPaddingRelative(mTvDefinition, 0, padding, padding, padding);
                            mTvDefinition.setText(key);
                            textView.setTextColor(Color.YELLOW);
                        }
                    }
                }
            }
        }
    }

    // 切换多媒体资源
    public void changeMedia(String sourceId, boolean isAudio) {
        changeMedia(sourceId, isAudio, -1);
    }

    // 切换多媒体资源
    public void changeMedia(String sourceId, boolean isAudio, int maxTime) {
        mIsPrepared = false;
        mIsAudio = isAudio;
        if (maxTime < 0) {
            mMaxSeekTime = -1;
        } else {
            mMaxSeekTime = maxTime * 1000;
        }
        pause();
        if (mOnStateChangedListener != null)
            mOnStateChangedListener.onChangeMedia(mDWMediaPlayer.getCurrentPosition() / 1000, mDWMediaPlayer.getDuration() / 1000);
        mDWMediaPlayer.stop();
        mDWMediaPlayer.reset();
        mDWMediaPlayer.setVideoPlayInfo(sourceId, USER_ID, API_KEY, verificationCode, getContext());
        mDWMediaPlayer.setSurface(mSurface);
        drmServer.reset();
        if (mIsAudio) {
            mDWMediaPlayer.setDefaultPlayMode(MediaMode.AUDIO, null);
        } else {
            mDWMediaPlayer.setDefaultPlayMode(MediaMode.VIDEO, null);
        }
        mDWMediaPlayer.setAudioPlay(mIsAudio);
        mSwitchDefPos = 0;
        mDWMediaPlayer.prepareAsync();
    }

    private Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            mBottomLayout.setVisibility(View.GONE);
            mListDefinitions.setVisibility(View.GONE);
            mTvTitleBack.setVisibility(View.GONE);
        }
    };

    private Runnable mProgressAndTimeInfoRunnable = this::updateProgressAndTimeInfo;
    // 开始播放
    private void start() {
         load_the_film.hide();
        if (!mDWMediaPlayer.isPlaying() && mIsPrepared) {
            mDWMediaPlayer.start();
            mIvPlayPause.setImageResource(R.drawable.ic_video_pause_small);
            if (mIsAudio) {
                mIvAudioGif.setVisibility(View.VISIBLE);
//                mIvFullHalf.setVisibility(View.INVISIBLE);
                if (!mIsViewDestroyed)
                    ImageLoaderKt.loadImageGifFit(mIvAudioGif, R.drawable.ic_audio_playing);
            } else {
                mIvAudioGif.setVisibility(View.GONE);
//                mIvFullHalf.setVisibility(View.VISIBLE);
            }
            mHandler.postDelayed(mHideRunnable, BOTTOM_LAYOUT_SHOW_TIME);
            mHandler.post(mProgressAndTimeInfoRunnable);
        }
    }
    // 暂停播放
    private void pause() {
        if (mDWMediaPlayer.isPlaying()) {
            mDWMediaPlayer.pause();
            if (mOnStateChangedListener != null && mIsPrepared)// 播放同一音视频时暂停，不是切换音视频时暂停
                mOnStateChangedListener.onPause(mDWMediaPlayer.getCurrentPosition() / 1000, mDWMediaPlayer.getDuration() / 1000);
            mBottomLayout.setVisibility(View.VISIBLE);
            mIvPlayPause.setImageResource(R.drawable.ic_video_play_small);
            if (mIsAudio) {
                mIvAudioGif.setVisibility(View.VISIBLE);
//                mIvFullHalf.setVisibility(View.INVISIBLE);
                if (!mIsViewDestroyed)
                    ImageLoaderKt.loadImageFit(mIvAudioGif, R.drawable.ic_audio_playing);
            } else {
                mIvAudioGif.setVisibility(View.GONE);
//                mIvFullHalf.setVisibility(View.INVISIBLE);
            }
            mHandler.removeCallbacks(mHideRunnable);
            mHandler.removeCallbacks(mProgressAndTimeInfoRunnable);
        }
    }

    // 更新播放进度和时间信息
    private void updateProgressAndTimeInfo() {
        if (mIsPrepared) {
            int currentPosition = mDWMediaPlayer.getCurrentPosition();
            int duration = mDWMediaPlayer.getDuration();
            int progress = currentPosition * 100 / duration;
            if (!mIsSeeking)
                mSeekBar.setProgress(progress);
            mTvTimeInfo.setText(millisecondsToMinuteSecondStr(currentPosition));
            mTvTimeInfo.append("/");
            mTvTimeInfo.append(millisecondsToMinuteSecondStr(duration));
            mHandler.postDelayed(mProgressAndTimeInfoRunnable, 1000L);
            if (mMaxSeekTime >= 0 && currentPosition > mMaxSeekTime) {
                mMaxSeekTime = currentPosition;
            }
        }
    }

    // 将毫秒转为分钟：秒
    private static String millisecondsToMinuteSecondStr(long ms) {
        int seconds = (int) (ms / 1000);
        String result = "";
        int min, second;
        min = seconds / 60;
        second = seconds - min * 60;

        if (min < 10) {
            result += "0" + min + ":";
        } else {
            result += min + ":";
        }
        if (second < 10) {
            result += "0" + second;
        } else {
            result += second;
        }
        return result;
    }

    @Override
    public void onDetach() {
        Log.e("走了ss","onDetach"+playvalue);
        super.onDetach();
    }
}









